﻿using System;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using UnityEngine;
using UnityEngine.SocialPlatforms;

public class Client : MonoBehaviour
{
    private string ip = "127.0.0.1";
    private int port = 8098;

    //创建 1个客户端套接字 和1个负责监听服务端请求的线程  
    private Thread threadclient = null;
    private Socket socketclient = null;

    private string info = "打印信息："+"\n";

    void Start()
    {
        StartConnect();
    }

    void OnGUI()
    {
        if (GUI.Button(new Rect(20, 5, 100, 20), "发送数据"))
        {
            System.Random random=new System.Random();
            ClientSend("传输数据测试"+random.Next(0,9999));
        }
        GUI.Label(new Rect(20,30, 200, 500), info);
    }

    void OnApplicationQuit()
    {
        socketclient.Close();
    }

    private void StartConnect()
    {
        //定义一个套接字监听  
        socketclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        //获取文本框中的IP地址  
        IPAddress address = IPAddress.Parse(ip);

        //将获取的IP地址和端口号绑定在网络节点上  
        IPEndPoint point = new IPEndPoint(address, port);

        try
        {
            //客户端套接字连接到网络节点上，用的是Connect  
            socketclient.Connect(point);
        }
        catch (Exception)
        {
            TipLog("连接失败");
            return;
        }

        threadclient = new Thread(ClientReceive);
        threadclient.IsBackground = true;
        threadclient.Start();
    }

    //发送字符信息到服务端的方法  
    void ClientSend(string message)
    {
        //将输入的内容字符串转换为机器可以识别的字节数组     
        byte[] bytes = Encoding.UTF8.GetBytes(message);
        //调用客户端套接字发送字节数组     
        socketclient.Send(bytes);
        //将发送的信息追加到聊天内容文本框中   
        TipLog("发送消息:"+message); 
    }

    // 接收服务端发来信息的方法    
    void ClientReceive()
    {
        //持续监听服务端发来的消息 
        while (true)
        {
            try
            {
                //定义一个1M的内存缓冲区，用于临时性存储接收到的消息  
                byte[] arrRecvmsg = new byte[1024 * 1024];

                //将客户端套接字接收到的数据存入内存缓冲区，并获取长度  
                int length = socketclient.Receive(arrRecvmsg);

                //将套接字获取到的字符数组转换为人可以看懂的字符串  
                string message = Encoding.UTF8.GetString(arrRecvmsg, 0, length);
                TipLog("收到消息:"+message);
                
            }
            catch (Exception e)
            {
                TipLog("远程服务器已经中断连接");
                break;
            }
        }
    }

    

    //获取当前系统时间  
    DateTime GetCurrentTime()
    {
        DateTime currentTime = new DateTime();
        currentTime = DateTime.Now;
        return currentTime;
    }

    private void TipLog(string tip)
    {
        info +=tip + "\n";
    }

}